package com.shujia.mysqlconection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcUtils {
    private static volatile JdbcUtils Instance ;
    private Connection conn;
    private JdbcUtils() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://192.168.205.129:3306/students?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8", "root","123456");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
    public static JdbcUtils getInstance(){
        if( Instance == null ){
            synchronized (JdbcUtils.class){
                if ( Instance == null ){
                    Instance = new JdbcUtils();
                    return Instance;
                }
            }
        }
        return Instance;
    }

    public boolean execute(String sql){
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            return preparedStatement.execute();
        } catch (SQLException e) {
            return false;
        }finally {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public void closeConnection(){
        if ( Instance != null ){
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException();
                }finally {
                    Instance = null;
                }

            }
        }
    }

}
